/*******************************************************************************
 *
 * Copyright (c) 2008-2011 ayound@gmail.com
 * This program and the accompanying materials
 * are made available under the terms of the GNU GENERAL PUBLIC LICENSE
 * which accompanies this distribution, and is available at
 * http://dev.perl.org/licenses/gpl1.html
 * All rights reserved.
 *
 * Created on 2009-11-10
 *******************************************************************************/

package org.ayound.skin.editor.core;

import java.awt.Color;
import java.awt.image.RGBImageFilter;

/**
 * HSBFilter. <br>
 *
 */
public class HSBFilter extends RGBImageFilter implements IColorConvert{

	/**
	 * the Hue of the indicated new foreground color.
	 */
	float hue = 0;

	/**
	 * the Saturation of the indicated new foreground color.
	 */
	float saturation = 100;

	/**
	 * the Brightness of the indicated new foreground color.
	 */
	float brightness = 100;

	public float getBrightness() {
		return brightness;
	}

	public void setBrightness(float brightness) {
		this.brightness = brightness;
	}

	public float getHue() {
		return hue;
	}

	public void setHue(float hue) {
		this.hue = hue;
	}

	public float getSaturation() {
		return saturation;
	}

	public void setSaturation(float saturation) {
		this.saturation = saturation;
	}

	public HSBFilter(){
		canFilterIndexColorModel = true;
	}

	/**
	 * Construct a HueFilter object which performs color modifications to warp
	 * existing image colors to have a new primary hue.
	 */
	public HSBFilter(Color fg) {
		float hsbvals[] = Color.RGBtoHSB(fg.getRed(), fg.getGreen(), fg.getBlue(), null);
		hue = hsbvals[0];
		saturation = hsbvals[1];
		brightness = hsbvals[2];
		canFilterIndexColorModel = true;
	}

	/**
	 * Filter an individual pixel in the image by modifying its hue, saturation,
	 * and brightness components to be similar to the indicated new foreground
	 * color.
	 */
	public int filterRGB(int x, int y, int rgb) {
		int alpha = (rgb >> 24) & 0xff;
		int red = (rgb >> 16) & 0xff;
		int green = (rgb >> 8) & 0xff;
		int blue = (rgb) & 0xff;
		float [] hsbValue = Color.RGBtoHSB(red, green, blue, null);
		float newHue = hsbValue[0] * (360-hue)/360;
		float newSaturation = hsbValue[1] * saturation/100;
		float newBrightness = hsbValue[2] * brightness/100;
		if(newHue>1){
			newHue = 1;
		}
		if(newHue<0){
			newHue = 0;
		}
		if(newSaturation>1){
			newSaturation = 1;
		}
		if(newSaturation<0){
			newSaturation = 0;
		}
		if(newBrightness>1){
			newBrightness = 1;
		}
		if(newBrightness<0){
			newBrightness = 0;
		}
		rgb = Color.HSBtoRGB(newHue, newSaturation, newBrightness);
		return (rgb & 0x00ffffff) | (alpha << 24);
	}

	public Color convert(Color color) {
		return new Color(filterRGB(0, 0, color.getRGB()));
	}

}
